package rpg.client.player.swing.game;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JPanel;

import rpg.client.Instruction;
import rpg.client.player.swing.GameJPanel;

public class InstructionsJPanel extends JPanel implements ActionListener {
	/**
     * 
     */
	private static final long serialVersionUID = -6723608223706426691L;

	static final int NUMBER_OF_BUTTONS = 10;
	private final MyButton[] buttons = new MyButton[NUMBER_OF_BUTTONS];
	private final GameJPanel game;

	public InstructionsJPanel(final GameJPanel gameJPanel) {
		super(new GridLayout(NUMBER_OF_BUTTONS, 1));
		game = gameJPanel;
		setPreferredSize(new Dimension(400, 300));
		for (int i1 = 0; i1 < NUMBER_OF_BUTTONS; i1++) {
			buttons[i1] = new MyButton(this);
			add(buttons[i1]);
		}
	}

	@Override
	public void actionPerformed(final ActionEvent e) {
		if (e.getSource() instanceof MyButton) {
			final MyButton mb = (MyButton) e.getSource();
			final Instruction i = mb.getInstruction();
			if (i != null) {
				System.out.println(i);
				game.request(i);
				game.requestFocus();
			}
		} else {
			System.out.println("WTF: " + e);
		}
	}

	public void updateInstructions(final List<Instruction> ins) {
		System.out.println(ins);
		for (int i1 = 0; i1 < NUMBER_OF_BUTTONS; i1++) {
			if (ins.size() > i1) {
				final Instruction i = ins.get(i1);
				buttons[i1].setInstruction(i);
			} else {
				buttons[i1].setInstruction(null);
			}
		}
	}
}

class MyButton extends JButton {
	/**
     * 
     */
	private static final long serialVersionUID = -7711405756853630521L;

	volatile Instruction instruction = null;

	public MyButton(final ActionListener listener) {
		super("?");
		setVisible(false);
		addActionListener(listener);
	}

	Instruction getInstruction() {
		return instruction;
	}

	void setInstruction(final Instruction i) {
		instruction = i;

		if (i == null) {
			setVisible(false);
		} else {
			setText(i.toString());
			setVisible(true);
		}
	}
}